<template>
  <div v-drag class="model" :style="`background-image:url(${bg});`">
    <header>
      <p>{{ title }}</p>
      <p @click="hideModel">X</p>
    </header>
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "model",
  props: ["bg", "title"],
  directives: {
    drag(el) {
      el.style.position = "absolute";
      let x;
      let y;
      let obj = JSON.parse(localStorage.getItem("location"));
      el.style.left = obj.left + "px";
      el.style.top = obj.top + "px";
      el.onmousedown = function(e) {
        x = e.pageX - el.offsetLeft;
        y = e.pageY - el.offsetTop;
        el.onmousemove = function(ee) {
          let left = ee.pageX - x;
          let top = ee.pageY - y;

          // 边界判断
          let minL = 0;
          let minT = 0;
          let maxL = document.documentElement.clientWidth - ee.offsetWidth;
          let maxT = document.documentElement.clientHeight - ee.offsetHeight;
          // 获取边界值
          // 如果 当前的拖拽位置 小于 0 的话 就是最小 0 否则就是最大 如果最大了那就是可视区域最大的位置否则还是原来的位置
          left = left < minL ? minL : left > maxL ? maxL : left;
          top = top < minT ? minT : top > maxT ? maxT : top;
          el.style.left = left + "px";
          el.style.top = top + "px";
          localStorage.setItem(
            "location",
            JSON.stringify({ left: left, top: top })
          );
        };
      };
      document.onmouseup = function() {
        el.onmousemove = null;
      };
    },
  },
  data() {
    return {};
  },
  mounted() {},
  methods: {
    hideModel() {
      this.$emit("hideModel");
    },
  },
  components: {},
};
</script>

<style lang="scss">
.model {
  width: 500px;
  height: 300px;
  background-color: rgb(179, 136, 136);
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-size: 100% 100%;
  background-repeat: no-repeat;

  header {
    width: 100%;
    height: 25px;
    background-color: rgb(38, 173, 207);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    &:hover {
      cursor: move;
    }
  }
  p {
    &:last-of-type {
      &:hover {
        cursor: pointer;
      }
    }
  }
}
</style>
